# -*- coding: utf-8 -*-
# File : food_service.py
# Author: taoyahui
# Date : 2021/10/17
from results import *
from utils import common_utils, id_utils
from services import user_service
from config import contract_name, contract_address, contract_abi
from models.food import Food
from models.create_food import CreateFood
import json


def create_food(json_dict, request):
    get_user_res = user_service.get_user_by_token(request)
    if get_user_res['code'] != 200:
        return json.dumps(get_user_res, ensure_ascii=False)
    user = get_user_res['data']
    name = json_dict['name']
    food_type = json_dict['food_type']
    quality = json_dict['quality']
    spec = json_dict['spec']
    other = json_dict['other']
    food_id = next(id_utils.unique_sequence)
    res = common_utils.common_bc_req(user.address, contract_name, 'createFood', [food_id, name, food_type, quality, spec, other],
                                     contract_address,
                                     contract_abi)

    if res.status_code == 200:
        res_json = json.loads(res.text)
        if res_json['status'] == '0x0':
            return success_result
        else:
            return gen_result(500, res_json['message'])
    else:
        return gen_result(res.status_code, res.text)


def get_food(json_dict, request):
    get_user_res = user_service.get_user_by_token(request)
    if get_user_res['code'] != 200:
        return json.dumps(get_user_res, ensure_ascii=False)
    user = get_user_res['data']
    food_id = json_dict['id']
    res = common_utils.common_bc_req(user.address, contract_name, 'getFood', [food_id],
                                     contract_address,
                                     contract_abi)
    if res.status_code == 200:
        food_arr = json.loads(res.text)
        food = Food(food_arr[0], food_arr[1], food_arr[2], food_arr[3], food_arr[4])
        return gen_result('200', food.__dict__)
    else:
        return gen_result(res.status_code, res.text)
    pass


def query_food(json_dict):
    page = json_dict['input_page']
    trans_list = CreateFood.query.order_by(CreateFood.pk_id.desc()).paginate(page, per_page=20, error_out = False).items
    trans_list = [item.to_json() for item in trans_list]
    total = CreateFood.query.count()
    return gen_result('200', {
        'total':total,
        'list':trans_list
    })